package excel.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public final class ExcelServer extends Thread {

    private final int port;
    // 线程池,最大循序
    private final ExecutorService executorService;

    public ExcelServer(int port, int poolSize) {
        this.port = port;
        executorService = Executors.newFixedThreadPool(poolSize);
    }

    @Override
    public void run() {

        Logger.info("Excel服务器启动了");
        Logger.info("尝试监听端口:" + port);
        final ServerSocket serverSocket;
        try {
            serverSocket = new ServerSocket(port);
            Logger.info("监听地址" + serverSocket.getInetAddress().getHostAddress());
        } catch (IOException e) {
            Logger.error("端口绑定出错(已经被占用/没有权限)", e);
            return;
        }


        Logger.info("启动完成");

        try {
            while (true) {
                final Socket socket = serverSocket.accept();
                final SocketCall socketCall = new SocketCall(socket);
                new Thread(new SocketDeamon(socketCall, socket)).start();
                executorService.execute(socketCall);
            }
            // accept一般不会exception,一但exception那么这个ServerSicket已经不可用了，所以try-catch一定要写在循环外
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
